from mesh_node import *

class parse_dump():
	"""
	Parses the dump file and generates a table of mesh nodes
	"""
	def __init__(self, dumpfilename, desfilename):
		self.dumpfilename = dumpfilename
		self.dumpfile = open(self.dumpfilename, 'r')
		self.entries = {}
		self.desfilename = desfilename
		self.desfile = open(self.desfilename, 'r')
		
	def parse(self):
		"""
		Start parsing the dump file
		"""
		while(True):
			node = self.get_next_record()
			if not node:
				break
			try:
				self.entries[node.id].name = node.name
				self.entries[node.id].id = node.id
				self.entries[node.id].parent = self.entries[node.parent]
				self.entries[node.id].des_pos = node.des_pos
			except KeyError:
				self.entries[node.id] = node
			
			if(node.parent != -1):
				try:
					self.entries[node.parent].add_child(self.entries[node.id])
				except KeyError:
					self.entries[node.parent] = mesh_node(None, 0)
					self.entries[node.parent].add_child(self.entries[node.id])
				self.entries[node.id].parent = self.entries[node.parent]
		self.dumpfile.close()
		
	def get_next_record(self):
		"""
		Gets the next record
		"""
		file = self.dumpfile
		id = file.readline()[:-1]
		if not id:
			return None
		name = file.readline()[:-1]
		parent = file.readline()[:-1]
		pos = file.readline()[:-1]
		record = mesh_node(id, name, parent=parent)
		record.des_pos = pos
		file.readline()
		return record
		
	def invert_dict(self):
		"""
		Takes the entries with id as the key and returns a new dict with names as the key
		Returns a special dictionary whose value for any key is a list
		"""
		invert = mdict()
		for (id, node) in self.entries.items():
			invert[node.name] = node

		return invert
		
	def generate_description(self, node):
		"""Obvious"""
		self.desfile.seek(int(node.des_pos))
		des = self.extract_description()
		print des

	def extract_description(self):
		"""
		Takes a record and extracts the description string from there
		"""
		while True:
			line = self.desfile.readline()[:-1]
			if not line:
				return None
			if line[:3] == 'MS ':
				entries = line.split('=')
				des = entries[1].strip()
				return des
			
if __name__ == '__main__':
	dump = parse_dump('dump', 'MESH/ascii/d2007.bin')
	dump.parse()
	table = dump.entries
	sample = table['D12.776.124.486.485.705.750.530.500']
	sample_parent = sample.parent
	print 'parent of D12.776.124.486.485.705.750.530.500 is', sample_parent.name, sample_parent.id
	inverse = dump.invert_dict()
	mam = inverse['Mammary Glands, Human']
	parent = mam[0].parent
	print 'parent of (Mammary Glands, Human) is', parent.name, parent.id
	dump.generate_description(sample)
